<template>
  <textarea ref="textareaRef" v-model="text" @input="adjustHeight"></textarea>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const textareaRef = ref(null)
    const text = ref('')

    const adjustHeight = () => {
      if (textareaRef.value) {
        textareaRef.value.style.height = 'auto' // 重置高度
        const newHeight = textareaRef.value.scrollHeight

        // 设置最大高度，超出时显示滚动条
        const maxHeight = 200 // 最大高度
        if (newHeight > maxHeight) {
          textareaRef.value.style.height = `${maxHeight}px`
          textareaRef.value.style.overflow = 'auto' // 显示滚动条
        } else {
          textareaRef.value.style.height = `${newHeight}px`
          textareaRef.value.style.overflow = 'hidden' // 隐藏滚动条
        }
      }
    }
    onMounted(() => {
      adjustHeight() // 初始化时调整高度
    })

    return {
      textareaRef,
      text,
      adjustHeight,
    }
  },
}
</script>
<style scoped>
textarea {
  border: none;
  outline: none;
  width: 100%;
  resize: none;
  font-size: 16px;
  font-family: inherit;
}

textarea {
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: #888 #f1f1f1; /* Firefox */
}

/* Chrome, Safari */
textarea::-webkit-scrollbar {
  width: 8px;
}

textarea::-webkit-scrollbar-thumb {
  background-color: #888;
}

textarea::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
